//
//  RightTableViewCell.m
//  GoBigMarket
//
//  Created by 李真 on 16/8/16.
//  Copyright © 2016年 legend. All rights reserved.
//

#import "RightTableViewCell.h"
#import "MyProductsTool.h"
#import "WelcomViewController.h"
static NSInteger newNum;//存储num变化后的数，在网络请求成功时：num = newNum;
@implementation RightTableViewCell{
    
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code

}
#pragma mark - 查询数据库
-(void)layoutSubviews{
    self.model.productCount = [MyProductsTool queryByCondition:self.model.Id];
    if (self.model.productCount == 0) {
        _productNum.hidden = YES;
        _subtractBtn.hidden = YES;
    }else{
        _productNum.hidden = NO;
        _subtractBtn.hidden = NO;
    }
//#pragma mark - 查询本地数据库
    DLog(@"rightCell—--: %d || %d",[MyProductsTool queryByCondition:self.model.Id],self.model.Id);
    [self provideNumSetText];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    // Configure the view for the selected state
}

//添加到购物车
- (IBAction)addBtn:(id)sender {
    
    /**判断是否登录
     */
    NSUserDefaults * userLogon = [NSUserDefaults standardUserDefaults];
    NSString * isSignin_String = [userLogon objectForKey:LOGIN_STATUS];
    NSLog(@"等没等。。。%@",isSignin_String);
    if ([isSignin_String isEqualToString:@"未登录"]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您还没有登录,请先登录后再执行操作!" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"前去登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alert dismissViewControllerAnimated:YES completion:nil];
            WelcomViewController *welcomeVC = [[WelcomViewController alloc]init];
            UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:welcomeVC];
            [UIApplication sharedApplication].keyWindow.rootViewController = nav;
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alert dismissViewControllerAnimated:YES completion:nil];
        }]];
        [self.viewController presentViewController:alert animated:YES completion:nil];
        
    }else if([isSignin_String isEqualToString:@"已登录"]){
        newNum = self.model.productCount + 1;
        if (self.model.productCount == 0) {
            [self addShoppingCar];
        }else{
            [self changNum];
        }
    }
}

#pragma mark - 减
- (IBAction)subtractBtn:(id)sender {
    /**判断是否登录
     */
    NSUserDefaults * userLogon = [NSUserDefaults standardUserDefaults];
    NSString * isSignin_String = [userLogon objectForKey:LOGIN_STATUS];
    NSLog(@"等没等。。。%@",isSignin_String);
    if ([isSignin_String isEqualToString:@"未登录"]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您还没有登录,请先登录后再执行操作!" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"前去登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alert dismissViewControllerAnimated:YES completion:nil];
            WelcomViewController *welcomeVC = [[WelcomViewController alloc]init];
            UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:welcomeVC];
            [UIApplication sharedApplication].keyWindow.rootViewController = nav;
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alert dismissViewControllerAnimated:YES completion:nil];
        }]];
        [self.viewController presentViewController:alert animated:YES completion:nil];
        
    }else if([isSignin_String isEqualToString:@"已登录"]){
        if (self.model.productCount > 0) {
            newNum = self.model.productCount - 1;
            if (newNum == 0) {
                [self deleteNum];
            }else{
                [self changNum];
            }
        }
    }
}

#pragma mark -  显示操作
- (void)provideNumSetText{
    //读取数据库中相应的信息
//    _productNum.text = [NSString stringWithFormat:@"%d",[MyProductsTool queryByCondition:self.model.Id]];
    
    _productNum.text = [NSString stringWithFormat:@"%ld",self.model.productCount];
}

#pragma mark - 购物车加减操作
- (void)changNum{
    
    [CQNetWorkTools POSTWithURL:PostOperationShoppingCar par:@{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,@"Duuid":GETUUID,@"ProductID":[NSString stringWithFormat:@"%d",self.model.Id],@"Count":[NSString stringWithFormat:@"%ld",newNum]} success:^(id responseObject) {
        DLog(@"修改购物车 ：%@",responseObject);
        NSInteger err =[[responseObject valueForKey:@"Err"]integerValue];
        
        if (err == 0) {
            self.model.productCount = newNum;
#pragma mark - 保存修改数据
            [MyProductsTool ClickJiaJianProduct:self.model.Id andCount:self.model.productCount blockcompletion:^(BOOL updata) {
                if (updata) {
                   [self provideNumSetText];
                }
            }];
            //#pragma mark - 查询本地数据库
            DLog(@"rightCell—--: %d || %d",[MyProductsTool queryByCondition:self.model.Id],self.model.Id);
            
            [self provideNumSetText];
//购物车红点显示
//            [self creatRedDian];
        }else {
          [self createAlertControllerWithMessage:[responseObject valueForKey:@"msg"]];
        }
        
    } filed:^(NSError *error) {
        DLog(@"修改购物车 error ：%@",error);
    }];
}
#pragma mark - 加入购物车
- (void)addShoppingCar{
    
    //加入购物车
    [CQNetWorkTools POSTWithURL:PostAddshoppingCar par:@{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,@"Duuid":GETUUID,@"ProductID":[NSString stringWithFormat:@"%d",self.model.Id],@"Count":[NSString stringWithFormat:@"%ld",newNum]} success:^(id responseObject) {
        DLog(@"加入购物车 ：%@",responseObject);
        NSInteger err =[[responseObject valueForKey:@"Err"]integerValue];
        
        if (err == 0) {
            self.model.productCount = newNum;
#pragma mark - 保存修改数据
            [MyProductsTool ClickJiaJianProduct:self.model.Id andCount:self.model.productCount blockcompletion:^(BOOL updata) {
                if (updata) {
                    _subtractBtn.hidden = NO;
                    _productNum.hidden = NO;
                    [self provideNumSetText];
                }
            }];
            //#pragma mark - 查询本地数据库
            DLog(@"rightCell—--: %d || %d",[MyProductsTool queryByCondition:self.model.Id],self.model.Id);
//            _productNum.hidden = NO;
//            _subtractBtn.hidden = NO;
//            [self creatRedDian];
        }else{
            [self createAlertControllerWithMessage:[responseObject valueForKey:@"msg"]];
        }
        
    } filed:^(NSError *error) {
      
    }];
}
#pragma mark - 删除商品
- (void)deleteNum{
    
    [CQNetWorkTools POSTWithURL:PostRemoveFromCart par:@{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,@"Duuid":GETUUID,@"ProductID":[NSString stringWithFormat:@"%d",self.model.Id]}  success:^(id responseObject) {
        
        if ([[responseObject valueForKey:@"Err"]intValue] == 0) {
             self.model.productCount = newNum;
#pragma mark - 保存修改数据
            [MyProductsTool deleteOneProductsFromSQL:self.model.Id];
//#pragma mark - 查询本地数据库
            DLog(@"rightCell—--: %d || %d",[MyProductsTool queryByCondition:self.model.Id],self.model.Id);
            _productNum.hidden = YES;
            _subtractBtn.hidden = YES;
            [self provideNumSetText];
//            [self creatRedDian];
        }else{

            [self createAlertControllerWithMessage:[responseObject valueForKey:@"msg"]];
        }
        DLog(@"删除购物车里的商品: %@",responseObject);
    } filed:^(NSError *error) {
        
    }];
}

#pragma mark - model
-(void)setModel:(ClassIfProductModel *)model{
    if (_model != model) {
        _model = model;
    }
    if (!self.model.productCount) {
        self.model.productCount = 0;
    }
    if (self.model.productCount == 0) {
        _productNum.hidden = YES;
        _subtractBtn.hidden = YES;
    }
    self.productNum.text = [NSString stringWithFormat:@"%ld",self.model.productCount];
    
    self.productName.text = [_model.ProductName stringByRemovingPercentEncoding];

    [self.productPrice setAttributedText:[self priceLabelWithStr:[NSString stringWithFormat:@"售价:%.2f元",self.model.MinSalePrice]]];
    self.productSales.text = [NSString stringWithFormat:@"销量:%d",_model.SaleCounts];
    if (self.model.ImagePath.length > 0) {

        NSString *url = [NSString stringWithFormat:@"%@%@",ReleaseORDebug,self.model.ImagePath];
        DLog(@"分类页商品图片网址Url__ %@",url);
        [self.productPic sd_setImageWithURL:[NSURL URLWithString:url]placeholderImage:[UIImage imageNamed:@"未上传图片"]];
    }else{
        self.productPic.image = [UIImage imageNamed:@"未上传图片"];
    }
}
//修改image大小
- (UIImage *)image:(UIImage*)image byScalingToSize:(CGSize)targetSize {
    UIImage *sourceImage = image;
    UIImage *newImage = nil;
    
    UIGraphicsBeginImageContext(targetSize);
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = CGPointZero;
    thumbnailRect.size.width  = targetSize.width;
    thumbnailRect.size.height = targetSize.height;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage ;
}

- (NSAttributedString *)priceLabelWithStr:(NSString *)str{
    //售价
        
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
   
       [attributedString addAttribute:NSForegroundColorAttributeName value:XNColor(236, 152, 18, 1) range:NSMakeRange(3, str.length - 3)];
       [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:NSMakeRange(3, str.length - 3)];
    
    return attributedString;
}

#pragma mark - 获取购物车
- (void)creatRedDian{
    if (GETShopId) {
    [CQNetWorkTools POSTWithURL:ShopCartGetProducts par:@{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN, @"Duuid":GETUUID,@"ShopId":GETShopId} success:^(id responseObject) {
        
        self.viewController.navigationController.tabBarController.viewControllers[2].tabBarItem.badgeValue = [NSString stringWithFormat:@"%@", [responseObject objectForKey:@"TotalCount"]];
        
        if ([[NSString stringWithFormat:@"%@", [responseObject objectForKey:@"TotalCount"]] isEqualToString:@"0"]) {
            self.viewController.navigationController.tabBarController.viewControllers[2].tabBarItem.badgeValue = nil;
        }
    } filed:^(NSError *error) {
        DLog(@"%@", error);
    }];
    }
}
#pragma mark - 弹出框
- (void)createAlertControllerWithMessage:(NSString *)message {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertController addAction:cancelAction];
    [self.viewController presentViewController:alertController animated:YES completion:^{
        
    }];
}
@end
